package controller;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import jpa.exceptions.NonexistentEntityException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import model.Obat;
import model.ObatQuery;
import model.HistoryOrder;
import model.HistoryOrderQuery;
import model.UserQuery;
import model.User;

 /**
   *
   * @author atikahSH
   *
   */

public class AccountLogic {

    HttpServletRequest request;

    public AccountLogic(HttpServletRequest request) {
        this.request = request;
    }

    public String signUp() throws NoSuchAlgorithmException {
        User user = new User();//create
        UserQuery uq = new UserQuery();
        List<Obat> obats = new ArrayList<Obat>();
        ObatQuery eq = new ObatQuery();
        HttpSession session = request.getSession();

        String nama = request.getParameter("nama");
        String alamat = request.getParameter("alamat");
        String telepon = request.getParameter("telepon");
        String email = request.getParameter("email");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");

        if (username != null) {
            user.setNama(nama);
            user.setAlamat(alamat);
            user.setTelepon(telepon);
            user.setEmail(email);
            user.setUsername(username);

            MessageDigest mdEnc = MessageDigest.getInstance("MD5"); 
            mdEnc.update(password.getBytes(), 0, password.length());
            String md5 = new BigInteger(1, mdEnc.digest()).toString(16); 
            user.setPassword(md5);
            user.setAdminStat(0);
            session.setAttribute("tempReg", user);
        } else {
            session.setAttribute("error", "masih ada field kosong");
            return "register.jsp";
        }

        
        if (nama.equals("") || alamat.equals("") || telepon.equals("")
                || email.equals("") || username.equals("") || password.equals("")) {
            session.setAttribute("error", "masih ada field kosong");
            return "register.jsp";
        }/*validasi input*/ else {
            if (password.equals(confirmPassword)) {
                /*pesan error selain angka*/
                try {
                    int telp = Integer.parseInt(telepon);
                } catch (NumberFormatException nfe) {
                    session.setAttribute("error", "format telepon harus angka");
                    return "register.jsp";
                }
                if (password.length() > 5) {
                    boolean hasilCheck = uq.checkUser(username);
                    if (!hasilCheck) {
                        uq.createApoteker(user);
                        session.removeAttribute("uname");
                        session.removeAttribute("tempReg");
                        return "index.jsp";
                    }/*pesan error ketika username sama*/ else {
                        session.setAttribute("error", "username sudah terpakai");
                        return "register.jsp";
                    }
                } /*pesan error ketika password kurang dari 6*/ else {
                    session.setAttribute("error", "password minimal 6");
                    return "register.jsp";
                }
            } else {
                session.setAttribute("error", "konfirmasi password salah");
                return "register.jsp";
            }
        }
    }


    public String lihatProfil() {
        HttpSession session = request.getSession();
        User user = new User();
        UserQuery uq = new UserQuery();
        List<Obat> obats = new ArrayList<Obat>();
        ObatQuery eq = new ObatQuery();
        if (session.getAttribute("uname") != null) {
            User uname = (User) session.getAttribute("uname");
            String username = uname.getUsername();
            boolean hasilCheck = uq.checkUser(username);
            /* cek AdminStat*/
            if (hasilCheck) {
                user = uname;
                /*redirect ke halaman profil Administrator jika admin status = 1*/
                if (user.getAdminStat() == 1) {
                    return "profilAdmin.jsp";
                }/*redirect ke halaman profil Apoteker jika admin status = 0*/ else {
                    return "profil.jsp";
                }
            }/*redirect ke halaman utama jika username tidak ditemukan*/ else {
                session.setAttribute("error", "username tidak ada");
                obats = eq.getLimitedObats();
                request.setAttribute("obats", obats);
                session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");//ngambil obats
                return "index.jsp";
            }
        } else {
            session.setAttribute("error", "sudah logout sebelumnya");
            obats = eq.getLimitedObats();
            request.setAttribute("obats", obats);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
            return "index.jsp";
        }
    }


    public String lihatProfilPublic() {
        HttpSession session = request.getSession();
        User user = new User();
        UserQuery uq = new UserQuery();
        String temp = request.getParameter("idUser");
        int idUser = Integer.parseInt(temp);
        user = uq.getUser(idUser);
        request.setAttribute("user", user);
        return "profilPublic.jsp";
    }

    public String loggedIn() throws NoSuchAlgorithmException {
        HttpSession session = request.getSession();
        User user = new User();
        UserQuery uq = new UserQuery();
        List<Obat> obats = new ArrayList<Obat>();
        ObatQuery eq = new ObatQuery();
        String username = request.getParameter("username");
        String md5 = request.getParameter("password");
        MessageDigest mdEnc = MessageDigest.getInstance("MD5");
        mdEnc.update(md5.getBytes(), 0, md5.length());
        String password = new BigInteger(1, mdEnc.digest()).toString(16);
        if (username != null) {
            user.setUsername(username);
            session.setAttribute("tempLog", user);
        } else {
            session.setAttribute("error", "masih ada field kosong");
            obats = eq.getLimitedObats();
            request.setAttribute("obats", obats);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
            return "index.jsp";
        }
        if (username.equals("") || password.equals("")) {
            session.setAttribute("error", "masih ada field kosong");
            obats = eq.getLimitedObats();
            request.setAttribute("obats", obats);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
            return "index.jsp";
        } else {
            boolean hasilCheck = uq.checkUser(username);
            if (hasilCheck) {
                user = null;
                user = uq.getUser(username);

                if (username.equals(user.getUsername()) && password.equals(user.getPassword())) {
                    session.setAttribute("uname", user);//set session uname yang nanti diambil berapa kali
                    session.removeAttribute("tempLog");
                    if (user.getAdminStat() == 1) {
                        return "profilAdmin.jsp";
                    } else {
                        return "profil.jsp";
                    }
                } else {
                    session.setAttribute("error", "username/password salah");
                    obats = eq.getLimitedObats();
                    request.setAttribute("obats", obats);
                    session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
                    return "index.jsp";
                }
            } else {
                session.setAttribute("error", "username tidak ada");
                obats = eq.getLimitedObats();
                request.setAttribute("obats", obats);
                session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
                return "index.jsp";
            }
        }
    }


    public String logout() {
        HttpSession session = request.getSession();
        List<Obat> obats = new ArrayList<Obat>();
        ObatQuery eq = new ObatQuery();
        if (session.getAttribute("uname") != null) {
            session.removeAttribute("ename");
            session.removeAttribute("uname");
            obats = eq.getLimitedObats();
            request.setAttribute("obats", obats);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
            return "index.jsp";
        } else {
            session.setAttribute("error", "sudah logout sebelumnya");
            obats = eq.getLimitedObats();
            request.setAttribute("obats", obats);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
            return "index.jsp";
        }
    }


    public String ubahProfil() {
        HttpSession session = request.getSession();
        User user = new User();
        UserQuery uq = new UserQuery();
        List<Obat> obats = new ArrayList<Obat>();
        ObatQuery eq = new ObatQuery();

        if (session.getAttribute("uname") != null) {
            User uname = (User) session.getAttribute("uname");
            boolean hasilCheck = uq.checkUser(uname.getUsername());
            if (hasilCheck) {
                user = uname;
                session.setAttribute("tempEdit", user);
                return "editProfil.jsp";
            } else {
                session.setAttribute("error", "username tidak ada");
                obats = eq.getLimitedObats();
                request.setAttribute("obats", obats);
                session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
                return "index.jsp";
            }
        } else {
            session.setAttribute("error", "sudah logout sebelumnya");
            obats = eq.getLimitedObats();
            request.setAttribute("obats", obats);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
            return "index.jsp";
        }
    }


    public String simpanUbahProfil() throws NoSuchAlgorithmException {
        HttpSession session = request.getSession();
        User user = new User();
        UserQuery uq = new UserQuery();
        List<Obat> obats = new ArrayList<Obat>();
        ObatQuery eq = new ObatQuery();

        String nama = request.getParameter("nama");
        String alamat = request.getParameter("alamat");
        String telepon = request.getParameter("telepon");
        String email = request.getParameter("email");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        if (session.getAttribute("uname") != null) {
            user = (User) session.getAttribute("uname");
            String tempUname = user.getUsername();
            if (username != null) {
                user.setNama(nama);
                user.setAlamat(alamat);
                user.setTelepon(telepon);
                user.setEmail(email);
                user.setUsername(username);
                MessageDigest mdEnc = MessageDigest.getInstance("MD5"); // Encryption algorithm
                mdEnc.update(password.getBytes(), 0, password.length());
                String md5 = new BigInteger(1, mdEnc.digest()).toString(16); // Encrypted string
                user.setPassword(md5);
                session.setAttribute("tempEdit", user);
            } else {
                session.setAttribute("error", "masih ada field kosong");
                return "editProfil.jsp";
            }

            if (nama.equals("") || alamat.equals("") || telepon.equals("")
                    || email.equals("") || password.equals("")) {
                session.setAttribute("error", "masih ada field kosong");
                return "editProfil.jsp";
            } else {
                if (password.equals(confirmPassword)) {

                    try {
                        int telp = Integer.parseInt(telepon);
                    } catch (NumberFormatException nfe) {
                        session.setAttribute("error", "format telepon harus angka");
                        return "editProfil.jsp";
                    }
                    if (password.length() > 5) {
                        boolean hasilCheck = uq.checkUser(username);
                        if (!hasilCheck || username.equals(tempUname)) {
                            session.setAttribute("uname", user);
                            uq.editUser(user);
                            session.removeAttribute("tempEdit");
                            if (user.getAdminStat() == 1) {
                                return "profilAdmin.jsp";
                            } else {
                                return "profil.jsp";
                            }
                        } else {
                            session.setAttribute("error", "username sudah terpakai");
                            return "editProfil.jsp";
                        }
                    } else {
                        session.setAttribute("error", "password minimal 6");
                        return "editProfil.jsp";
                    }
                } else {
                    session.setAttribute("error", "konfirmasi password salah");
                    return "editProfil.jsp";
                }
            }
        } else {
            session.setAttribute("error", "sudah logout sebelumnya");
            obats = eq.getLimitedObats();
            request.setAttribute("obats", obats);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
            return "index.jsp";
        }
    }


    public String hapusApoteker() throws NonexistentEntityException {
        HttpSession session = request.getSession();
        String idUser = request.getParameter("idUser");
        List<User> users = new ArrayList<User>();
        UserQuery uq = new UserQuery();
        List<Obat> obats = new ArrayList<Obat>();
        ObatQuery eq = new ObatQuery();
        List<HistoryOrder> historyOrders = new ArrayList<HistoryOrder>();
        HistoryOrderQuery hpq = new HistoryOrderQuery();

        if (session.getAttribute("uname") != null) {
            if (idUser == null) {
                users = uq.getApotekers();
                request.setAttribute("users", users);
            } else {
                int id = Integer.parseInt(idUser);
                User temp = uq.getUser(id);
                obats = eq.getMyObats(temp);
                if (obats != null) {
                    Iterator<Obat> iteratorE = obats.iterator();
                    while (iteratorE.hasNext()) {
                        Obat nextE = iteratorE.next();
                        historyOrders = hpq.getHistoryOrders(nextE);
                        if (historyOrders != null) {
                            Iterator<HistoryOrder> iteratorH = historyOrders.iterator();
                            while (iteratorH.hasNext()) {
                                HistoryOrder nextH = iteratorH.next();
                                hpq.deleteHistoryOrder(nextH.getIdOrder());
                            }
                        }
                        eq.deleteObat(nextE.getIdObat());
                    }
                }
                uq.deleteApoteker(id);
                users = uq.getApotekers();//mengambil apoteker yang masih ada (belum di hapus)
                request.setAttribute("users", users);//menampilkan kembali
            }
            return "daftarApoteker.jsp";
        } else {
            session.setAttribute("error", "sudah logout sebelumnya");
            obats = eq.getLimitedObats();
            request.setAttribute("obats", obats);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
            return "index.jsp";
        }
    }

    public String home() {
        HttpSession session = request.getSession();
        List<Obat> obats = new ArrayList<Obat>();
        ObatQuery eq = new ObatQuery();
        String show;
        if (request.getParameter("show") != null) {
            show = request.getParameter("show");
        } else {
            show = "limited";
        }
        session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
        if (session.getAttribute("uname") == null) {
            if (show.equals("all")) {
                obats = eq.getAllObats();
                request.setAttribute("obats", obats);
                session.setAttribute("show", "<a href='account?page=home'>Five Recent Obats</a>");
                return "index.jsp";
            } else {
                obats = eq.getLimitedObats();
                request.setAttribute("obats", obats);
                session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Obats</a>");
                return "index.jsp";
            }
        } else {
            if (show.equals("all")) {
                obats = eq.getAllObats();
                request.setAttribute("obats", obats);
                session.setAttribute("show", "<a href='account?page=home'>Five Recent Obats</a>");
                return "home.jsp";
            } else {
                obats = eq.getLimitedObats();
                request.setAttribute("obats", obats);
                session.setAttribute("show", "<a href='account?page=home&&show=all'>show all obats</a>");
                return "home.jsp";
            }
        }
    }
}
